package com.bw.a2207a.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.bw.a2207a.base.BaseBean
import com.bw.a2207a.base.BaseViewModel
import com.bw.a2207a.bean.BannerBean
import com.bw.a2207a.bean.LoginBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *
 * @ClassName: LoginViewModel
 * @Description: java类作用描述
 * @Author: zhangyanchao
 * @CreateDate: 2024/10/17 11:28 AM
 * @Version: 1.0
 */
class LoginViewModel : BaseViewModel() {

    val loginLiveData = MutableLiveData<BaseBean<LoginBean>>()

    val loginFlowData = MutableSharedFlow<BaseBean<LoginBean>>()

    val bannerLiveData = MutableLiveData<BaseBean<List<BannerBean>>>()

    /**
     * 调用服务方法，实现登录
     * @param map HashMap<String, String>
     */
    fun login(map: HashMap<String, String>) {
        //开启协程，发送网络请求
        viewModelScope.launch(Dispatchers.IO) {
            val resutl = apiService.login(map)
            loginLiveData.postValue(resutl)
        }
    }


    /**
     * 通过flow，发送事件，实现登录功能
     * @param map HashMap<String, String>
     */
    fun loginFlow(map: HashMap<String, String>) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                val resutl = apiService.login(map)
                loginFlowData.emit(resutl)
                //通过buffer 缓存解决背压问题
                loginFlowData.buffer()
            }
        }

    }


    fun getBanner() {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                bannerLiveData.postValue(apiService.getBanner())

            }
        }
    }
}